package zjut.raymond.collectorplus.ui;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import zjut.raymond.collectorplus.R;
import zjut.raymond.collectorplus.adapter.SelectListAdapter;
import zjut.raymond.collectorplus.pojo.Area;
import zjut.raymond.collectorplus.util.ApiResult;
import zjut.raymond.collectorplus.util.Constant;
import zjut.raymond.collectorplus.view.CustomRadioButton;
import zjut.raymond.collectorplus.view.CustomTitleView;
import zjut.raymond.collectorplus.view.SelectorGroup;
import zjut.raymond.collectorplus.vm.MainViewModel;


public class AreaSelectedFragment extends Fragment {
    public static final String TAG = "AreaSelectedFragment";
    public static final int MSG_BUSINESS = 0x27;
    public static final int MSG_BUILDINGS = 0x28;
    public static final int MSG_FLOORS = 0x29;
    public static final int MSG_BUSINESS_CHANGED = 0x30;
    public static final int MSG_BUILDINGS_CHANGED = 0x31;
    public static final int MSG_FLOORS_CHANGED = 0x32;

    private MainViewModel viewModel;
    private ScheduledExecutorService executorService;
    private Handler handler;
    private CustomRadioButton cbtn_unit, cbtn_building, cbtn_floor;
    private TextView tv_area_type;
    private TextView tv_tip;
    private RecyclerView recyclerView;
    private SelectListAdapter businessAdapter, buildingAdapter, floorAdapter;
    private CustomTitleView customTitleView;

    public AreaSelectedFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        Log.d(TAG, "onCreateView: ");
        return inflater.inflate(R.layout.fragment_area_selected, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Log.d(TAG, "onViewCreated: ");
        viewModel = new ViewModelProvider(getActivity()).get(MainViewModel.class);
        executorService = Executors.newScheduledThreadPool(10);
        if (viewModel.getBusinessNumber() == 0) {
            executorService.execute(rqBusinessRunnable);
        }
        initView();
        initHandler();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.d(TAG, "onActivityCreated: ");
    }

    private void initHandler() {
        handler = new Handler(Looper.myLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                switch (msg.what) {
                    case MSG_BUSINESS: {
                        tv_area_type.setText("单位");
                        List<Area> list = viewModel.getBusinesses();
                        if (list != null && list.size() > 0) {
                            tv_tip.setVisibility(View.GONE);
                            recyclerView.setVisibility(View.VISIBLE);
                            businessAdapter.setList(list);
                            businessAdapter.notifyDataSetChanged();
                            recyclerView.swapAdapter(businessAdapter, false);
                        } else {
                            tv_tip.setVisibility(View.VISIBLE);
                            recyclerView.setVisibility(View.GONE);
                        }
                        break;
                    }
                    case MSG_BUILDINGS: {
                        tv_area_type.setText("建筑");
                        List<Area> list = viewModel.getBuildings();
                        if (list != null && list.size() > 0) {
                            tv_tip.setVisibility(View.GONE);
                            recyclerView.setVisibility(View.VISIBLE);
                            buildingAdapter.setList(list);
                            buildingAdapter.notifyDataSetChanged();
                            recyclerView.swapAdapter(buildingAdapter, false);
                        } else {
                            tv_tip.setVisibility(View.VISIBLE);
                            recyclerView.setVisibility(View.GONE);
                        }
                        break;
                    }
                    case MSG_FLOORS: {
                        tv_area_type.setText("楼层");
                        List<Area> list = viewModel.getFloors();
                        if (list != null && list.size() > 0) {
                            tv_tip.setVisibility(View.GONE);
                            recyclerView.setVisibility(View.VISIBLE);
                            floorAdapter.setList(list);
                            floorAdapter.notifyDataSetChanged();
                            recyclerView.swapAdapter(floorAdapter, false);
                        } else {
                            tv_tip.setVisibility(View.VISIBLE);
                            recyclerView.setVisibility(View.GONE);
                        }
                        break;
                    }

                    case MSG_BUSINESS_CHANGED: {
                        Area business = viewModel.getCurrentBusiness().getValue();
                        cbtn_unit.setInfo((business != null) ? business.getName() : "未选择");
                        cbtn_building.setInfo("未选择");
                        cbtn_floor.setInfo("未选择");
                        viewModel.clearBuildings();
                        if (business != null) {
                            executorService.execute(rqBuildingRunnable);
                        }
                        viewModel.clearCurrentBuilding();
                        break;
                    }

                    case MSG_BUILDINGS_CHANGED: {
                        Area building = viewModel.getCurrentBuilding().getValue();
                        cbtn_building.setInfo((building != null) ? building.getName() : "未选择");
                        cbtn_floor.setInfo("未选择");
                        viewModel.clearFloors();
                        if (building != null) {
                            executorService.execute(rqFloorRunnable);
                        }
                        viewModel.clearCurrentFloor();
                        break;
                    }

                    case MSG_FLOORS_CHANGED: {
                        Area floor = viewModel.getCurrentFloor().getValue();
                        cbtn_floor.setInfo((floor != null) ? floor.getName() : "未选择");
                        break;
                    }
                    default: {
                        super.handleMessage(msg);
                        break;
                    }
                }
            }
        };
    }

    private void initView() {
        //标题
        customTitleView = getView().findViewById(R.id.ctv_select_area);
        customTitleView.setLeftOnClickListener(v -> {
            NavController controller = Navigation.findNavController(v);
            controller.navigate(R.id.action_areaSelectedFragment_to_mainFragment);
        });

        tv_area_type = getView().findViewById(R.id.tv_area_type);
        tv_area_type.setText("未选择");

        tv_tip = getView().findViewById(R.id.tv_tips);
        tv_tip.setVisibility(View.VISIBLE);
        //RecyclerView
        recyclerView = getView().findViewById(R.id.recyclerview_select);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        businessAdapter = new SelectListAdapter();
        buildingAdapter = new SelectListAdapter();
        floorAdapter = new SelectListAdapter();

        businessAdapter.setOnItemClickListener((view, position) -> {
            Area business = businessAdapter.getList().get(position);
            viewModel.setCurrentBusiness(business);
            handler.sendEmptyMessage(MSG_BUSINESS_CHANGED);
        });
        buildingAdapter.setOnItemClickListener((view, position) -> {
            Area building = buildingAdapter.getList().get(position);
            viewModel.setCurrentBuilding(building);
            handler.sendEmptyMessage(MSG_BUILDINGS_CHANGED);
        });
        floorAdapter.setOnItemClickListener((view, position) -> {
            Area floor = floorAdapter.getList().get(position);
            viewModel.setCurrentFloor(floor);
            handler.sendEmptyMessage(MSG_FLOORS_CHANGED);
        });

        recyclerView.setAdapter(businessAdapter);
        recyclerView.setVisibility(View.GONE);

        //左侧选择栏
        SelectorGroup selectorGroup = new SelectorGroup();
        selectorGroup.setChoiceMode(SelectorGroup.MODE_SINGLE_CHOICE);
        selectorGroup.setStateListener((groupTag, tag, isSelected) -> {
            switch (tag) {
                case Constant.TYPE_BUSINESS: {
                    handler.sendEmptyMessage(MSG_BUSINESS);
                    break;
                }
                case Constant.TYPE_BUILDING: {
                    handler.sendEmptyMessage(MSG_BUILDINGS);
                    Area business = viewModel.getCurrentBusiness().getValue();
                    if (business == null || business.getId().equals("")) {
                        Toast.makeText(getContext(), "请先选择单位！", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                case Constant.TYPE_FLOOR: {
                    handler.sendEmptyMessage(MSG_FLOORS);
                    Area building = viewModel.getCurrentBuilding().getValue();
                    Area business = viewModel.getCurrentBusiness().getValue();
                    if (null == business || business.getId().equals("")) {
                        Toast.makeText(getContext(), "请先选择单位！", Toast.LENGTH_SHORT).show();
                    } else if (null == building || building.getId().equals("")) {
                        Toast.makeText(getContext(), "请先选择建筑！", Toast.LENGTH_SHORT).show();
                    } else {
                        tv_tip.setVisibility(View.VISIBLE);
                        recyclerView.setVisibility(View.GONE);
                    }
                    break;
                }
                default:
                    break;
            }
        });
        cbtn_unit = getView().findViewById(R.id.costom_button_unit);
        cbtn_building = getView().findViewById(R.id.costom_button_building);
        cbtn_floor = getView().findViewById(R.id.costom_button_floor);
        cbtn_unit.setGroup("single", selectorGroup);
        cbtn_building.setGroup("single", selectorGroup);
        cbtn_floor.setGroup("single", selectorGroup);
    }

    Runnable rqBusinessRunnable = new Runnable() {
        @Override
        public void run() {
            HttpRequest.get(Constant.RQ_BUSINESS_URL, new BaseHttpRequestCallback<ApiResult>() {
                @Override
                protected void onSuccess(ApiResult apiResult) {
                    JSONObject dataJo = JSON.parseObject(JSON.toJSONString(apiResult.getData()));
                    JSONArray jsonArray = JSONArray.parseArray(dataJo.getString("list"));
                    Log.d(TAG, "onSuccess: " + jsonArray);
                    for (Object o : jsonArray) {
                        if (o instanceof JSONObject) {
                            JSONObject jo = (JSONObject) o;
                            String id = jo.getString("id");
                            String name = jo.getString("name");
                            viewModel.addBusiness(new Area(id, ("".equals(name)) ? "未知地点" : name));

                        }
                    }
                }
            });
        }
    };


    Runnable rqBuildingRunnable = new Runnable() {
        @Override
        public void run() {
            String businessId = viewModel.getCurrentBusiness().getValue().getId();
            HttpRequest.get(Constant.RQ_BUILDING_URL + "/" + businessId, new BaseHttpRequestCallback<ApiResult>() {
                @Override
                public void onStart() {
                    super.onStart();
                }

                @Override
                protected void onSuccess(ApiResult apiResult) {
                    JSONObject dataJo = JSON.parseObject(JSON.toJSONString(apiResult.getData()));
                    JSONArray jsonArray = JSONArray.parseArray(dataJo.getString("list"));
                    Log.d(TAG, "onSuccess: " + jsonArray);
                    for (Object o : jsonArray) {
                        if (o instanceof JSONObject) {
                            JSONObject jo = (JSONObject) o;
                            //   viewModel.addBusiness(new Area(jo.getString("id"), jo.getString("name")));
                            String id = jo.getString("id");
                            String name = jo.getString("name");
                            viewModel.addBuilding(new Area(id, ("".equals(name)) ? "未知建筑" : name));
                            Log.d(TAG, "onSuccess: " + viewModel.getBuildingsNumber());
                        }
                    }
                }
            });
        }
    };

    Runnable rqFloorRunnable = new Runnable() {
        @Override
        public void run() {
            String buildingId = viewModel.getCurrentBuilding().getValue().getId();
            HttpRequest.get(Constant.RQ_FLOOR_URL + "/" + buildingId, new BaseHttpRequestCallback<ApiResult>() {
                @Override
                public void onStart() {
                    super.onStart();
                    //   viewModel.clearFloors();
                }

                @Override
                protected void onSuccess(ApiResult apiResult) {
                    JSONObject dataJo = JSON.parseObject(JSON.toJSONString(apiResult.getData()));
                    JSONArray jsonArray = JSONArray.parseArray(dataJo.getString("list"));
                    for (Object o : jsonArray) {
                        if (o instanceof JSONObject) {
                            JSONObject jo = (JSONObject) o;
                            String id = jo.getString("id");
                            String name = jo.getString("code");
                            viewModel.addFloor(new Area(id, ("".equals(name)) ? "未知楼层" : name));
                        }
                    }
                }
            });
        }
    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        viewModel.clearBuildings();
        viewModel.clearFloors();
    }
}